package org.shiro.serialize;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.*;

/**
 * @author LENOVO
 * FastByteRedisSerializer: 序列化成字节数组
 */
public class FastByteRedisSerializer implements RedisSerializer {
  @Override
  public byte[] serialize(Object o) throws SerializationException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    ObjectOutputStream obj;
    try {
      obj = new ObjectOutputStream(bytes);
      obj.writeObject(o);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return bytes.toByteArray();
  }

  @Override
  public Object deserialize(byte[] bytes) throws SerializationException {
    if (bytes == null) {
      return null;
    }

    ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
    ObjectInputStream objIn;
    Object obj;
    try {
      objIn = new ObjectInputStream(byteIn);
      obj = objIn.readObject();
    } catch (IOException | ClassNotFoundException e) {
      e.printStackTrace();
      return null;
    }
    return obj;
  }
}
